<template>
	<view>
		<view class="formwidth">
			<u-form class="uformwidth" :model="form" ref="addressForm">
				<u-form-item label="姓名" label-width="100rpx" prop="consignee">
					<u-input placeholder="请输入姓名" type="text" height="30" v-model="form.consignee" />
				</u-form-item>
				<u-form-item label="手机号" label-width="150rpx" prop="phone">
					<u-input placeholder="请输入手机号" type="text" height="30" v-model="form.phone" />
				</u-form-item>
				<u-form-item label="收货地址" label-width="180rpx">
					<view  @click="getAddress">
						<u-input placeholder="请输入收货地址" type="text" height="30" 
						v-model="form.location" suffixIcon="map" disabled />
					</view>
				</u-form-item>
				<u-form-item label="详细地址" label-width="180rpx" prop="detailedAddress">
					<u-input placeholder="请输入详细地址" type="text" height="30" v-model="form.detailedAddress" />
				</u-form-item>
			</u-form>
		</view>
		<button class="btn" @click.native="submit">{{formState?"保存修改":"新增地址"}}</button>
	</view>
</template>

<script>
	import {setUserAddress} from "apis/farmer/address.js"
	import addressRules from "utils/verify/addressRules.js"
	import {chooseLocation} from "utils/location.js"
	export default {
		data() {
			return {
				formState: 0, // 表单状态，0表示添加，1表示修改
				form: {
					id: "", //
					consignee: '', //联系人
					phone: '', //电话
					isDefault: 0,
					location: '点击选择地址', //收货地址地区
					detailedAddress: '', //详细地址
				},
				rules: addressRules
			}
		},
		methods: {
			async getAddress(){
				try {
					const {address,name} = await chooseLocation()
					this.form.location = address
					this.form.detailedAddress = name
				}catch(e){
					this.$errorMsg("地址选择失败")
				}
			},
			submit() {
				this.$refs.addressForm.validate().then(async valid => {
					if (valid) {
						const {code,msg} = await setUserAddress(this.form)
						if(code !== 200) return this.$errorMsg(msg)
						this.$store.dispatch("loadAddress")
						this.$successMsg(this.form.id?"修改成功":"添加成功")
						this.goback()
					}
				});
			}

		},
		onLoad() {
			const item = this.$Route.query
			if(item.id){
				this.form = item
				this.formState = 1
			}
		},
		onReady() { 
			this.$refs.addressForm.setRules(this.rules);
		}
	}
</script>

<style scoped>
	page {
		background-color: #FFFFFF;
	}
	.formwidth{
		width: 90vw;
		margin-left: 5vw;
		box-sizing: border-box;
	}
	::v-deep .u-icon__icon{
		font-size: 16px !important;
	}

	.btn {
		width: 92%;
		height: 80rpx;
		background-color: rgba(255, 87, 51, 1);
		margin-top: 50rpx;
		box-sizing: border-box;
		color: #FFFFFF;
		font-size: 36rpx;
		line-height: 80rpx;
		border-radius: 10rpx;
	}
</style>
